<template>
  <div class="chat-container">
    <!-- 顶部：用户名 -->
    <div class="chat-header">{{ userName }}</div>

    <!-- 中部：消息列表 -->
    <div class="chat-messages" ref="messageContainer">
      <div
        class="chat-message"
        v-for="(msg, index) in messages"
        :key="msg.messageId || index"
        :class="{ 'from-me': msg.fromMe }"
      >
        <!-- 头像：非本人消息显示在左，本人消息显示在右 -->
        <div class="chat-message" :class="{ 'from-me': msg.fromMe }">
          <img :src="msg.avatar" class="avatar" alt="avatar" />
          <div class="message-bubble">{{ msg.content }}</div>
        </div>
      </div>
    </div>

    <!-- 底部：输入栏 -->
    <div class="chat-input">
      <input
        v-model="input"
        type="text"
        placeholder="请输入消息"
        @keyup.enter="sendMessage"
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineProps, watch, nextTick } from 'vue'
import { useAccountStore } from '@/stores/useAccountStore'
import { getSessionMessage } from '@/apis/message'
import {
  connectSocket,
  sendSocketMessage,
  closeSocket,
} from '@/utils/websocket'

const props = defineProps({
  sessionId: Number,
  userName: String,
  targetId: Number,
})

const accountStore = useAccountStore()
const currentUserId = accountStore.uid
const currentUserAvatar = accountStore.avatar || 'https://default.avatar.png'
const messages = ref([])
const input = ref('')

const handleWebSocketMessage = (msg) => {
  if (msg.sessionId === props.sessionId) {
    const fromMe = msg.senderId === currentUserId
    const avatar = fromMe
      ? currentUserAvatar
      : avatarMap.value[msg.senderId] || 'https://default.avatar.png'

    messages.value.push({
      messageId: msg.messageId,
      sessionId: msg.sessionId,
      senderId: msg.senderId,
      receiverId: msg.receiverId,
      content: msg.content,
      isRead: msg.isRead,
      time: msg.createTime,
      fromMe: msg.senderId == currentUserId,
      avatar,
    })
    scrollToBottom()
  }
}

// 建立WebSocket连接
const setupWebSocket = () => {
  const url = `ws://localhost:8080/ws/chat-socket?userId=${currentUserId}`
  connectSocket(url, handleWebSocketMessage)
}

const avatarMap = ref({}) // 存储 senderId 对应的头像

const fetchMessages = async () => {
  try {
    const res = await getSessionMessage(props.sessionId)
    if (res?.code === '200' && Array.isArray(res.data)) {
      const map = {}
      res.data.forEach((item) => {
        map[item.senderId] = item.avatar
      })
      avatarMap.value = map

      messages.value = res.data.map((item) => ({
        ...item,
        fromMe: item.senderId == currentUserId,
      }))
      scrollToBottom()
    }
  } catch (err) {
    console.error('获取消息失败：', err)
  }
}

const messageContainer = ref(null)

const scrollToBottom = () => {
  nextTick(() => {
    const container = messageContainer.value
    if (container) {
      container.scrollTop = container.scrollHeight
    }
  })
}

// 发送消息
const sendMessage = () => {
  if (!input.value.trim()) return

  const messageData = {
    sessionId: props.sessionId,
    content: input.value.trim(),
    senderId: currentUserId,
    receiverId: props.targetId,
  }

  sendSocketMessage(messageData)
  input.value = ''
}

// 生命周期
onMounted(() => {
  fetchMessages()
  setupWebSocket()
})

// 监听sessionId变化（如果支持动态切换会话）
watch(
  () => props.sessionId,
  () => {
    closeSocket()
    setupWebSocket()
  }
)

onUnmounted(() => {
  closeSocket()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 600px;
  border: 1px solid #eee;
  background: #fff;
}

.chat-header {
  padding: 12px 16px;
  font-weight: bold;
  font-size: 16px;
  border-bottom: 1px solid #eee;
  background-color: #f8f8f8;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #fafafa;
}

.chat-message {
  margin-bottom: 10px;
  display: flex;
  align-items: flex-end;
}

.chat-message.from-me {
  flex-direction: row-reverse;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 16px;
  background-color: #e6f0ff;
  max-width: 85%;
  white-space: pre-wrap;
  overflow-wrap: break-word;
}

.chat-message.from-me .message-bubble {
  background-color: #d1ffd1;
}

.avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  margin: 0 8px;
  object-fit: cover;
  border: 1px solid #ccc;
}

.chat-input {
  display: flex;
  padding: 10px;
  border-top: 1px solid #eee;
  background: #fff;
}

.chat-input input {
  flex: 1;
  padding: 8px 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 8px;
  font-size: 14px;
}

.chat-input button {
  padding: 8px 16px;
  font-size: 14px;
  border: none;
  background-color: #409eff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}
</style>
